import React,{Component} from "react";
import {withRouter} from "react-router-dom";
import { Button, BackTop, Affix, Modal, message} from "antd";
import Header from "../component/header.js";
import SearchBannerS from "../utils/searchBannerS.js";
import Footer from "../component/footer.js";
import '../assets/stylesheets/search.css';
import moment from 'moment';

const format = "YYYY-MM-DD";
const minHour = 1, limitHour = 2;

class Search extends Component{
    constructor(props){
        super(props);
        this.state = {
            //直接从表单获取用户上次查询的信息
            initalValues:(()=>{
                let values = {
                    trip:"0",//0单程，1双程
                    goCity:"西安",
                    toCity:"北京",
                    goDate:moment().format(format),
                    toDate:moment().format(format),
                    classType:"0",
                    checkChild: false,
                    checkBaby: false,
                };
                if(this.props.location.values){//有从首页传过来的参数保存到session中。
                    let p_values = this.props.location.values;
                    sessionStorage.setItem("searchValues",  JSON.stringify(p_values));
                    return {...p_values,goDate: p_values.goDate, toDate: p_values.toDate}; 
                }else{ 
                    let s_values = JSON.parse(sessionStorage.getItem("searchValues"));
                    //如果是直接到这个页面的session里面没有值的，就使用默认的值初始化
                    return s_values?{...s_values, goDate: s_values.goDate, toDate: s_values.toDate}: values; 
                }
            })(),
            data:[],
            bookState: sessionStorage.getItem("bookState") || "1",//"0"：选第一趟，"1"：选最后一趟，如果是只有一趟就是一趟，默认只有一趟
            goTrip:{},
            goType:"",//对应舱型
            ModalVisible: false,
        }
    }
    componentDidMount(){
        localStorage.removeItem("valuesS");
    }
    onRef = (ref) =>{
        //基本上没用上，好像可以不用，最好也不要用
        this.getData = ref;
    }
    onGetData = (data) => {
        this.setState({data: data});
    }
    fixChange = (flag) =>{
        let dom = document.getElementsByClassName("search-condition-box")[0];
        if(dom){
            if(flag === true){
                dom.style.borderTop = "solid #238c8b 1px";
                dom.style.boxShadow = "#908f8f 0 0 3px";
            }else{
                dom.style.border = "none";
                dom.style.boxShadow = "none";
            }
        }
    }
    airplaneEnter = (e) =>{ if(e.target.nextElementSibling)e.target.nextElementSibling.style.display = "block"; }
    airplaneLeave = (e) =>{  if(e.target.nextElementSibling)e.target.nextElementSibling.style.display = "none"; }
    openClick = (e) =>{
        //打开的时候就显示阴影，
        let parent = e.target.parentElement.parentElement.parentElement,
            next = e.target.parentElement.parentElement.nextElementSibling;
        //点击打开和关闭
        if( e.target.getAttribute("data-open") === "false"){
            e.target.setAttribute("data-open","true");
            e.target.innerHTML="<span>收 起</span>";
        }else{
            e.target.setAttribute("data-open","false");
            e.target.innerHTML="<span>展 开</span>";
        }
        //关闭展开显示
        if(next){
            next.style.display === "none"?next.style.display = "block":next.style.display = "none";
            // 如果当前是打开的将当前设置为选中状态，其他的设置为非选中状态，当前是关闭的将当前的设置为非选中状态。
            next.style.display === "none"?parent.setAttribute("data-selected", "false"):parent.setAttribute("data-selected","true");
        }
    }
    onSelectTrip = (value) =>{
        if(value === "0"){
            console.log("选中单程的bookState为1");
            this.setState({bookState: "1"});
            sessionStorage.setItem("bookState", "1");
        }else{
            console.log("因为选中的是往返，所以设置了预定状态为0");
            this.setState({bookState: "0"});
            sessionStorage.setItem("bookState", "0");
        }
    }
    bookClick = (e) =>{
        //获得预定哪个航班的座位信息
        let number = e.target.getAttribute("data-number").split("-"),
            data = this.state.data,
            initalValues = JSON.parse(sessionStorage.getItem("searchValues")),
            path = {pathname:"/book", values:{goTrip:{}, goType:"", toTrip:{}, toType:""}};
        e.preventDefault();
        console.log("book点击预定", number, e.target);
        //在这里查找航班的信息并设置
        
        if(localStorage.getItem("username")){
            if(initalValues.trip === "1"){
                if(this.state.bookState === "0"){//设置去路程
                    for(let i in data){
                        if(data[i].id === number[0]){
                            //获取返程数据
                            this.setState({
                                goTrip: data[i], 
                                goType: number[1],
                                bookState: "1",
                                data:[]
                            });
                            this.getData({...initalValues, bookState: "1"});
                            break;
                        }
                    }
                }else{//设置返回路程，并提交
                    //把选中的这个航班的所有信息传过去？？？？
                    for(let i in data){
                        if(data[i].id === number[0] ){
                            //首先往返不冲突的时候才进行预定
                            let flag = 1,
                                goEnd = moment(this.state.goTrip.end.time),
                                toStart = moment(data[i].start.time);

                                if(goEnd.unix() + 3600 * minHour > toStart.unix()){//往返间隔不能小于1小时,unix获取的时间戳是秒
                                message.error("往返行程冲突或者间隔小于1小时，请重新选择");
                                flag = 0;
                            }else if(goEnd.unix() + 3600 * limitHour > toStart.unix() ){//返程小于到达后的2小时
                                message.warning("请注意，往返时间间隔小于2小时");
                            }
                            if(flag){
                                path.values.goTrip = this.state.goTrip;
                                path.values.goType = this.state.goType;
                                path.values.toTrip = data[i];
                                path.values.toType = number[1];
                                this.props.history.push(path);
                            }
                            break;
                        }
                    }
                    
                }
            }else{
                //设置去的路程，并提交
                for(let i in data){
                    if(data[i].id === number[0]){
                        path.values.goTrip = data[i];
                        path.values.goType = number[1];
                        this.props.history.push(path);
                        break;
                    }
                }
            }
        }else{
            this.setState({ModalVisible:true});
        }
        
    }
    handleOk = () =>{
        this.props.history.push({pathname:"/login"});
        this.setState({ModalVisible:false});
    }
    handleCancel = () =>{
        this.setState({ModalVisible:false});
    }
    render(){
        const initalValues = this.state.initalValues;
        const data = this.state.data;

        console.log("search-state-----------", this.state, sessionStorage.getItem("bookState"));
        return(
        <div>
            <Header></Header>
            <div id="search">
                <Affix offsetTop={40} onChange={this.fixChange}>
                    <div className="search-condition-box">
                        <SearchBannerS 
                            onRef={this.onRef} 
                            initalValues={initalValues} 
                            bookState = {this.state.bookState}
                            onGetData={this.onGetData}
                            onSelectTrip={this.onSelectTrip}
                        ></SearchBannerS>
                        <div className="search-history">
                            <span>历史查询</span>
                            <div className="items">
                                {}
                                <div data-infor="查询的每个字段的信息">
                                    <span className="trip">单程</span>
                                    <span className="go-city">北京</span>
                                    <span className="to-city">-重庆</span>
                                    <span className="go-date">2019-03-21</span>
                                </div>
                                <div>
                                    <span className="trip">往返</span>
                                    <span className="go-city">北京</span>
                                    <span className="to-city">-重庆</span>
                                    <span className="go-date">2019-03-21</span>
                                    <span className="back-date">--2019-03-23</span>
                                </div>
                                <div>
                                    <span className="trip">单程</span>
                                    <span className="go-city">西安</span>
                                    <span className="to-city">-重庆</span>
                                    <span className="go-date">2019-03-21</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </Affix>
                <div className="search-list">
                    <div className="head">
                        <span>航班信息</span>
                        <span>起飞时间</span>
                        <span>到达时间</span>
                        <span>价格</span>
                    </div>
                    <Modal title="提示" 
                        wrapClassName="vertical-center-modal"
                        visible={this.state.ModalVisible} 
                        onCancel={this.handleCancel}
                        footer={[
                            <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>去登录</Button>,
                            <Button key="back" type="ghost" onClick={this.handleCancel}>取 消</Button>,
                        ]}
                    >
                        <p>请登陆后再预定</p>
                    </Modal>
                    <div className="items">
                        {(()=>{
                            //当是往返的石时候要判断用哪个data。
                            if(!data.length){
                                return <div className="null"><p>没有符合条件的结果</p></div>
                            }
                            return data.map((v,index,arr)=>{
                                return (<div className="item" data-selected={false}>
                                    <div className="before">
                                        <div className="company">
                                            <div className="company">
                                                <b>{v.flight.company}</b>
                                            </div>
                                            <div className="airplane">
                                                <p onMouseEnter={this.airplaneEnter} onMouseLeave={this.airplaneLeave}>
                                                    {(()=>{
                                                        let type = "小型";
                                                        switch(v.flight.type){
                                                            case 1:type = "中型";break;
                                                            case 2:type = "大型";break;
                                                            case 3:type = "巨型";break;
                                                        }
                                                        return v.flight.plane + " " + "(" + type + "机)";
                                                    })()}
                                                </p>
                                                <div className="detail" style={{display:"none"}} >
                                                    <div className="plain">
                                                        <p><span>机型</span><span>{(()=>{
                                                            return v.flight.plane + " ";
                                                        })()}</span></p>
                                                        <p><span>类型</span><span>{v.flight.type}</span></p>
                                                        <p><span>餐食</span><span>{(()=>{
                                                           return v.flight.food === 0?"无":v.flight.food === 1?"正餐":"小食";
                                                        })()}</span></p>
                                                    </div>
                                                    <div className="class">
                                                        {v.economyClass?<div className="type">
                                                            <div>经济舱</div>
                                                            <div>
                                                                <p>座位间距：{v.economyClass.space}cm</p>
                                                                <p>座位宽度：{v.economyClass.width}cm</p>
                                                                <p>可倾斜度：{v.economyClass.angle}°</p>
                                                            </div>
                                                        </div>
                                                        :[]}
                                                        {v.businessClass?<div className="type">
                                                            <div>商务舱</div>
                                                            <div>
                                                                <p>座位间距：{v.businessClass.space}cm</p>
                                                                <p>座位宽度：{v.businessClass.width}cm</p>
                                                                <p>可倾斜度：{v.businessClass.angle}°</p>
                                                            </div>
                                                        </div>
                                                        :[]}
                                                        {v.firstClass?<div className="type">
                                                            <div>头等舱</div>
                                                            <div>
                                                                <p>座位间距：{v.firstClass.space}cm</p>
                                                                <p>座位宽度：{v.firstClass.width}cm</p>
                                                                <p>可倾斜度：{v.firstClass.angle}°</p>
                                                            </div>
                                                        </div>
                                                        :[]}
                                                        {}
                                                        {/* <div className="type">
                                                            <div>经济舱</div>
                                                            <div>
                                                                <p>座位间距：{v.flight.economyClassSpace}cm</p>
                                                                <p>座位宽度：{v.flight.economyClassWidth}cm</p>
                                                                <p>可倾斜度：{v.flight.economyClassAngle}°</p>
                                                            </div>
                                                        </div> */}
                                                    </div>
                                                </div>
                                            </div>
                                                
                                        </div>
                                        <div className="go">
                                            <p className="time">
                                                <b>{moment(v.start.time).format("HH:mm")}</b>
                                            </p>
                                            <p className="port">{v.start.airport}</p>
                                        </div>
                                        <div className="arrow">
                                            <img src={require("../assets/images/arrow.png")}></img>
                                        </div>
                                        <div className="to">
                                            <p className="time">
                                                <b>{moment(v.end.time).format("HH:mm")}</b>
                                            </p>
                                            <p className="port">{v.end.airport}</p>
                                        </div>
                                        <div className="price">
                                            <div>
                                                <span className="price-icon">￥</span>
                                                <span className="price-l">{(()=>{
                                                let arr = [];
                                                if(v.economyClass){ arr.push(v.economyClass.afterPrice); }
                                                if(v.businessClass){ arr.push(v.businessClass.afterPrice); }
                                                if(v.firstClass){ arr.push(v.firstClass.afterPrice); }
                                                return arr[0];
                                            })()}</span>起</div>
                                            <div className="discount">{v.economyClass?"经济舱"+(v.economyClass.discount*10)+"折":""}</div>
                                        </div>
                                        <div><Button onClick={this.openClick} data-open="false">展开</Button></div>
                                    </div>
                                    <div className="after" style={{display:"none"}}>
                                        {v.economyClass?<div>
                                            <span className={v.economyClass.repent === 0?"repent-free repent":"repent"}>{v.economyClass.repent === 0?"免费改期":"退改￥"+v.economyClass.repent}</span>
                                            <span className="luggage">托运行李额{v.economyClass.luggage}KG</span>
                                            <span className="class">经济舱{v.economyClass.discount === 1?"全价":(v.economyClass.discount*10)+"折"}</span>
                                            <span className={v.economyClass.residualTicket<10?"residualTicket-l":"residualTicket"}>余票<span>{v.economyClass.residualTicket}</span></span>
                                            <span className="after-price"><span>￥</span>{v.economyClass.afterPrice}</span>
                                            <span>
                                                <a>
                                                    <Button data-number={v.id + "-"  + 0} onClick={this.bookClick}>
                                                        {this.state.bookState === "1"?"订票":"选为去程"}
                                                    </Button>
                                                </a>
                                            </span>
                                        </div>:[]}
                                        {v.businessClass?<div>
                                            <span className={v.businessClass.repent===0?"repent-free repent":"repent"}>{v.businessClass.repent === 0?"免费改期":"退改￥"+v.businessClass.repent}</span>
                                            <span className="luggage">托运行李额{v.businessClass.luggage}KG</span>
                                            <span className="class">商务舱{v.businessClass.discount===1?"全价":(v.businessClass.discount*10)+"折"}</span>
                                            <span className={v.businessClass.residualTicket<10?"residualTicket-l residualTicket":"residualTicket"}>余票<span>{v.businessClass.residualTicket}</span></span>                                            
                                            <span className="after-price"><span>￥</span>{v.businessClass.afterPrice}</span>
                                            <span>
                                                <a>
                                                    <Button data-number={v.id + "-" + 1} onClick={this.bookClick}>
                                                        {this.state.bookState === "1"?"订票":"选为去程"}
                                                    </Button>
                                                </a>
                                            </span>
                                        </div>:[]}
                                        {v.firstClass?<div>
                                            <span className={v.firstClass.repent===0?"repent-free repent":"repent"}>{v.firstClass.repent === 0?"免费改期":"退改￥"+v.firstClass.repent}</span>
                                            <span className="luggage">托运行李额{v.firstClass.luggage}KG</span>
                                            <span className="class">头等舱{v.firstClass.discount===1?"全价":(v.firstClass.discount*10)+"折"}</span>
                                            <span className={v.firstClass.residualTicket<10?"residualTicket-l residualTicket":"residualTicket"}>余票<span>{v.firstClass.residualTicket}</span></span>                                            
                                            <span className="after-price"><span>￥</span>{v.firstClass.afterPrice}</span>
                                            <span>
                                                <a>
                                                    <Button data-number={v.id + "-" + 2} onClick={this.bookClick}>
                                                        {this.state.bookState === "1"?"订票":"选为去程"}
                                                    </Button>
                                                </a>
                                            </span>
                                        </div>:[]}
                                    </div>
                                </div>)
                            })
                        })()}
                    </div>
                </div>
                <div>
                    <BackTop visibilityHeight={300} />
                </div>
                <Footer></Footer>
            </div>
        </div>
        )
    }
}

export default withRouter(Search);
